package com.example.demo.Controller;

import com.example.demo.mathtest.Questions;
import com.example.demo.mathtest.RequestCollections;
import com.example.demo.mathtest.TM;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
public class Controller {

    @RequestMapping(value = "/problems", method = RequestMethod.GET)
    public ResponseEntity<Map<String, Object>> responseQuestions(@RequestParam Map<String, Object> paraMap) throws Exception {
        String envName = paraMap.get("env").toString();
        int grade = 1, num = 0;
        String openid = null;
        Questions questions;
        if (paraMap.containsKey("grade"))
            grade = Integer.parseInt(paraMap.get("grade").toString());
        if (paraMap.containsKey("num"))
            num = Integer.parseInt(paraMap.get("num").toString());
        if (paraMap.containsKey("openid"))
            openid = paraMap.get("openid").toString();
        questions = new Questions(grade);
        Map<String, Object> map = new HashMap<>();
        ArrayList<TM> details;
        switch (envName) {
            case "exercise":
            case "test":
                map.put("num", num);
                questions.mathQuestionsCreate(grade, num);
                details = questions.questionArrayList;
                map.put("details", details);
                break;
            case "review":
                questions.ErrorLoad(openid);
                details = questions.errorQuestionList;
                num = details.size();
                map.put("num", num);
                map.put("details", details);
                break;
        }
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    @PostMapping("/collections")
    public void postErrorQuestions(@RequestBody RequestCollections requestCollections) throws IOException {
        String envName = requestCollections.getEnv();
        String openid = requestCollections.getOpenid();
        Questions questions = new Questions(1);
        switch (envName) {
            case "review":
                int[] ordArray = requestCollections.getOrd4cancel();
                ArrayList<Integer> ordArrayList = new ArrayList<>();
                for (Integer o : ordArray) {
                    ordArrayList.add(o);
                }
                questions.deleteError(openid, ordArrayList);
                break;
            case "exercise":
            case "test":
                TM[] tmArray = requestCollections.getDetails();
                ArrayList<TM> tmArrayList = new ArrayList<>();
                Collections.addAll(tmArrayList, tmArray);
                questions.addError(openid, tmArrayList);
                break;
        }
    }
}
